package com.carefree.system.modules.security.filter;


import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.carefree.common.constant.UserConstant;
import com.carefree.common.utils.JwtUtils;
import com.carefree.system.modules.admin.service.LoginLogService;
import com.carefree.system.modules.security.entity.RedisUserDetails;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @ClassName:CustomerJwtAuthenticationTokenFilter
 * @Description: 步骤三: JWT登录授权过滤器
 * @Author Tengbin tengbin234@163.com
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private LoginLogService loginLogService;

    /**
     * 确保在一次请求中只通过一次filter，而不会重复执行
     * 在请求过来的时候,解析请求头中的token,再解析token得到用户信息,再存到SecurityContextHolder中
     *
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取请求头中的toen
        String token = request.getHeader("token");

        if (StringUtils.hasText(token)) {
            // 解析token中的用户标识信息
            String username = JwtUtils.parseTokenGetUsername(token);

            if (! StringUtils.isEmpty(username)) {
                RedisUserDetails redisUserDetails = JSONObject.parseObject(stringRedisTemplate.opsForValue().get(UserConstant.AUTH_USER_PREFIX + username), new TypeReference<RedisUserDetails>() {
                });

                if (Objects.nonNull(redisUserDetails) && SecurityContextHolder.getContext().getAuthentication() == null) {
                    // 设置security认证信息
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null, redisUserDetails.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }
        filterChain.doFilter(request, response);
    }
}
